package com.example.springboot_system.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.springboot_system.mapper.*;
import com.example.springboot_system.pojo.*;
import com.example.springboot_system.pojo.vo.MedicalVo;
import com.example.springboot_system.pojo.vo.outpatient.MedicalRecordReqVO;
import com.example.springboot_system.pojo.vo.outpatient.PatientInfoVO;
import com.example.springboot_system.service.OutpatientService;
import com.example.springboot_system.utils.GetId;
import com.example.springboot_system.utils.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class OutpatientServiceImpl implements OutpatientService {

    @Autowired(required = false)
    private PatientMapper patientMapper;
    @Autowired(required = false)
    private OutpatientQueueMapper outpatientQueueMapper;
    @Autowired(required = false)
    private MedicalRecordMapper medicalRecordMapper;
    @Autowired(required = false)
    private DrugMapper drugMapper;
    @Autowired(required = false)
    private RegisterMapper registerMapper;
    @Autowired(required = false)
    private DepartmentMapper departmentMapper;

    private GetId getId = new GetId();

    @Override
    public ResponseResult findMedicalRecord(String cardId, String prescriptionNum, HttpSession session) {
        //通过卡号拿到病人的ID
        QueryWrapper<Patient> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("card_id", cardId);
        Patient patient = patientMapper.selectOne(queryWrapper);

        //若为未收费的订单，则拿取它的挂号单ID，显示到处方门诊处方笺，若为收费的订单就不显示
        MedicalRecord medicalRecord1 = null;
        Register registerInfo = null;

        QueryWrapper<MedicalRecord> queryWrapper3 = new QueryWrapper<>();
        queryWrapper3.eq("prescription_num", prescriptionNum);
        medicalRecord1 = medicalRecordMapper.selectOne(queryWrapper3);
        /*        System.out.println("medicalRecord：" + medicalRecord1);*/
        /*            session.setAttribute("medicalRecord", medicalRecord1);*/

        //挂号单信息
        QueryWrapper<Register> queryWrapper4 = new QueryWrapper<>();
        queryWrapper4.eq("id", medicalRecord1.getRegisterId());
        registerInfo = registerMapper.selectOne(queryWrapper4);

        return new ResponseResult(200, "查询成功", medicalRecord1,registerInfo,patient);
    }


    @Override
    public ResponseResult buttonFind(String cardId, Integer outpatientQueueStatus, HttpSession session) {
        if (cardId == null || cardId == "") {
            return new ResponseResult(201, "请输入卡号");
        }
        if (outpatientQueueStatus == null) {
            return new ResponseResult(202, "请选择是否收费");
        }
        //拿到卡号，判断是否为空，同时通过卡号拿到病人的ID
        QueryWrapper<Patient> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("card_id", cardId);
        Patient patient = patientMapper.selectOne(queryWrapper);
        /*System.out.println("patient：" + patient);*/
        if (patient == null) {
            return new ResponseResult(203, "没有此卡号");
        }
        //通过病人的ID，和是否收费的状态state来查询OutpatientQueue记录,绑定回去页面
        QueryWrapper<OutpatientQueue> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("patient_id", patient.getId());
        queryWrapper1.eq("outpatient_queue_status", outpatientQueueStatus);
        List<OutpatientQueue> outpatientQueueList = outpatientQueueMapper.selectList(queryWrapper1);
        /*System.out.println("outpatientQueueList:::::::"+outpatientQueueList);*/
        if(outpatientQueueList.size()==0){
            return new ResponseResult(206,"未存在记录");
        }

        List<MedicalVo> medicalVoList = new ArrayList<>();
        int i=0;
        for(OutpatientQueue outpatient:outpatientQueueList){
            MedicalVo medicalVo = new MedicalVo();
            QueryWrapper<Register> queryWrapper5 = new QueryWrapper<>();
            queryWrapper5.eq("id",outpatient.getRegisterId());
            Register register11 = registerMapper.selectOne(queryWrapper5);

            QueryWrapper<MedicalRecord> queryWrapper6 = new QueryWrapper<>();
            queryWrapper6.eq("register_id",outpatient.getRegisterId());
            MedicalRecord medicalRecord11 = medicalRecordMapper.selectOne(queryWrapper6);
            System.out.println("medicalRecord11"+medicalRecord11);
            QueryWrapper<Department> queryWrapper7 = new QueryWrapper<>();
            queryWrapper7.eq("code",register11.getDepartment());
            Department department11 = departmentMapper.selectOne(queryWrapper7);

            medicalVo.setTime(outpatient.getCreateDatetime());
            medicalVo.setDepartmentName(department11.getName());
            medicalVo.setDoctorName(register11.getDoctor());
            if(medicalRecord11.getPrescriptionNum()==null){
                return new ResponseResult(205,"无该记录");
            }
            medicalVo.setPrescriptionNum(medicalRecord11.getPrescriptionNum());
            medicalVo.setRegisterType(register11.getRegisterType());

            medicalVoList.add(i,medicalVo);
            i++;
        }
        System.out.println("数据为"+medicalVoList);
        /*session.setAttribute("medicalVoList",medicalVoList);*/

        return new ResponseResult(200,medicalVoList);
    }

    // 更改/提交患者信息
    @Override
    public ResponseResult savePatientInfo(Patient patient) {
//        System.out.println(patient);
        QueryWrapper<Patient> wrapper = new QueryWrapper<>();
        wrapper.eq("card_id", patient.getCardId());
        int row = patientMapper.update(patient, wrapper);
        if (row != 1) {
            return new ResponseResult(201, "更新失败");
        }
        return new ResponseResult(200, "更新成功");
    }

//    @Override
//    public ResponseResult saveJudgeInfo(MedicalRecord medicalRecord, Patient patient, HttpSession session) {
//        User user = (User) session.getAttribute("user");
//        String doctorId = user.getId();
//        if (doctorId == null || doctorId.equals("")) {
//            return new ResponseResult(201, "会话已过期，请重新登录");
//        }
//        /*---------- 空值判断 ---------- */
//        String diagnosisResult = medicalRecord.getDiagnosisResult();
//        if (diagnosisResult == null || diagnosisResult.equals("")) {
//            return new ResponseResult(202, "初步诊断为空");
//        }
//        String conditionDescription = medicalRecord.getConditionDescription();
//        if (conditionDescription == null || conditionDescription.equals("")) {
//            return new ResponseResult(203, "主述为空");
//        }
//        String medicalOrder = medicalRecord.getMedicalOrder();
//        if (medicalOrder == null || medicalOrder.equals("")) {
//            return new ResponseResult(204, "医嘱为空");
//        }
//        /*---------- 空值判断 ---------- */
//
//        int row1 = medicalRecordMapper.insert(medicalRecord);
//        if (row1 != 1) {
//            return new ResponseResult(201, "未知错误，数据同步失败");
//        }
//        OutpatientQueue outpatientQueue = new OutpatientQueue();
//        outpatientQueue.setId(UUID.randomUUID().toString())
//                .setCreateDatetime(new Date())
//                .setOutpatientQueueStatus(0)
//                .setDescription(patient.getName() + "#" + user.getUsername())
//                .setRegisterId(medicalRecord.getRegisterId())
//                .setUserId(doctorId)
//                .setPatientId(patient.getId());
//        outpatientQueueMapper.insert(outpatientQueue);
//        return new ResponseResult(200, "门诊完成");
//    }

    // 获取所有药物
    @Override
    public ResponseResult getMedication() {
        List<Drug> drugs = drugMapper.findAllMedication();
        if (drugs == null) {
            return new ResponseResult(201, "没有药物");
        }

        return new ResponseResult(200, drugs);
    }

    // 获取病患信息
    @Override
    public ResponseResult getCardInfo(String cardId, HttpSession session) {
//        System.out.println("cardId:"+cardId);
        User user = (User) session.getAttribute("user");
        String doctorId = user.getId();
//        System.out.println("doctorId:"+doctorId);
        if (doctorId == null || doctorId == "") {
            return new ResponseResult(201, "会话已过期，请重新登录");
        }

        QueryWrapper<Register> wrapper = new QueryWrapper<>();
        wrapper.eq("doctor_id", doctorId);
        List<Register> list = registerMapper.selectList(wrapper);
        // System.out.println("\n");
        // System.out.println("list:"+list);
        if(list == null){
            return new ResponseResult(209,"未检测出挂号信息");
        }

        // 获取病患信息
        PatientInfoVO patientInfoVO = new PatientInfoVO();

        QueryWrapper<Patient> wrapper2 = new QueryWrapper<>();
        wrapper2.eq("card_id",cardId);
        Patient patient = patientMapper.selectOne(wrapper2);
        // System.out.println("\n");
        // System.out.println("patient:"+patient);

        QueryWrapper<Register> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("doctor_id",doctorId);
        wrapper1.eq("patient_id",patient.getId());
        wrapper1.eq("charge_status",0);
        wrapper1.eq("treatment_status",0);
//        System.out.println("patientId:"+patient.getId()+"\n");
        Register register = registerMapper.selectOne(wrapper1);
//        System.out.println("\n");
//        System.out.println(register);

        if (register == null){
            return new ResponseResult(210,"请先挂号");
        }
//        System.out.println("register:"+register);
        QueryWrapper<Department> wrapper3 = new QueryWrapper<>();
        wrapper3.eq("code",register.getDepartment());
        Department department = departmentMapper.selectOne(wrapper3);
//        System.out.println("department:"+department);
        patientInfoVO.setRegisterId(register.getId())
                    .setCardId(cardId)
                    .setName(patient.getName())
                    .setNationality(patient.getNationality())
                    .setSex(patient.getSex())
                    .setDepartment(department.getName())
                    .setAge(20)
                    .setMaritalStatus(patient.getMaritalStatus())
                    .setCareer(patient.getCareer())
                    .setPersonalHistory(patient.getPersonalHistory())
                    .setPastHistory(patient.getPastHistory())
                    .setFamilyHistory(patient.getFamilyHistory())
                    .setPrescriptionNum(register.getId())
                    .setPatientId(patient.getId())
                    .setDate(register.getCreateDatetime());
//        System.out.println("\n");
//        System.out.println(patientInfoVO);
//        System.out.println("\n");
        return new ResponseResult(200,patientInfoVO);
    }

    // 获取药物信息
    @Override
    public ResponseResult getMedicationInfo(String medicationName) {
        QueryWrapper<Drug> wrapper = new QueryWrapper<>();
        wrapper.eq("name",medicationName);
        return new ResponseResult(200,drugMapper.selectOne(wrapper));
    }

    // 提交门诊信息
    @Override
    public ResponseResult addMedicalRecord(HttpSession session, MedicalRecordReqVO medicalRecordReqVO) {
        System.out.println(medicalRecordReqVO+"\n");
        User user = (User) session.getAttribute("user");
        if (user == null){
            return new ResponseResult(201,"会话已过期，请重新登录");
        }
        String doctorID = user.getId();
        String doctorName = user.getUsername();

        /*↓↓↓↓↓↓ 空值判断 ↓↓↓↓↓↓*/

        /*↑↑↑↑↑↑ 空值判断 ↑↑↑↑↑↑*/
        /*↓↓↓↓↓↓ 插入数据 ↓↓↓↓↓↓*/
        MedicalRecord medicalRecord = new MedicalRecord();
        medicalRecord.setId(UUID.randomUUID().toString())
                    .setCreateDatetime(new Date())
                    .setConditionDescription(medicalRecordReqVO.getConditionDescription())
                    .setDiagnosisResult(medicalRecordReqVO.getDiagnosisResult())
                    .setDrugCost(medicalRecordReqVO.getDrugCost())
                    .setMedicalOrder(medicalRecordReqVO.getMedicalOrder())
                    .setPrescription(medicalRecordReqVO.getPrescription())
                    .setPrescriptionNum(getId.getPrescriptionNum())
                    .setRegisterId(medicalRecordReqVO.getRegisterId());
        int row = medicalRecordMapper.insert(medicalRecord);
        if (row != 1){
            return new ResponseResult(210,"数据插入失败，请联系管理员");
        }
        OutpatientQueue outpatientQueue = new OutpatientQueue();
        outpatientQueue.setId(UUID.randomUUID().toString())
                        .setCreateDatetime(new Date())
                        .setOutpatientQueueStatus(0)
                        .setDescription(medicalRecordReqVO.getPatientName()+"#"+doctorName)
                        .setRegisterId(medicalRecordReqVO.getRegisterId())
                        .setUserId(doctorID)
                        .setPatientId(medicalRecordReqVO.getPatientId());
        int row2 = outpatientQueueMapper.insert(outpatientQueue);
        if (row2 != 1){
            return new ResponseResult(211,"数据插入失败，请联系管理员");
        }
//        QueryWrapper<Register> wrapper3 = new QueryWrapper<>();
//        wrapper3.eq("id",medicalRecordReqVO.getRegisterId());
        Register register = new Register();
        register.setTreatmentStatus(1);
        register.setId(medicalRecordReqVO.getRegisterId());
//        registerMapper.update(register,wrapper3);
        registerMapper.updateById(register);
        /*↑↑↑↑↑↑ 插入数据 ↑↑↑↑↑↑*/
        return new ResponseResult(200,"门诊完成");
    }
}
